<template>
  <div>
    <van-nav-bar title="登录/注册" class="page-nav-bar">
      <template slot="left">
        <van-icon name="cross" @click="$router.back()" />
      </template>
    </van-nav-bar>
    <!-- 通过 pattern 进行正则校验 -->
    <van-form @submit="onSubmit" ref="userForm">
      <!-- 1 表单验证配置rules规则 -->
      <!-- 2 当表单提交的时候会自动触发表单验证 -->
      <!-- 3 验证通过才会触发提交事件 -->
      <van-field
        name="手机号"
        placeholder="请输入手机号"
        v-model="user.mobile"
        :rules="rules.mobile"
        type="number"
        maxlength="11"
        clearable
      >
        <i slot="left-icon" class="iconfont icon-shouji"></i>
      </van-field>
      <van-field
        name="验证码"
        placeholder="请输入验证码"
        v-model="user.code"
        :rules="rules.code"
        type="number"
        maxlength="6"
        clearable
        ><i slot="left-icon" class="iconfont icon-yanzhengma"></i
        ><template #button>
          <van-count-down @finish="countFinish" v-if="isCountDown" :time="1000 * 60">
            <template #default="timeData">
              <span class="block">{{ timeData.seconds }}</span>
            </template>
          </van-count-down>
          <van-button
            v-else
            class="verificationBtn"
            color="#ededed"
            round
            native-type="button"
            @click="onSendSms"
            :disabled="isSend"
            >获取验证码</van-button
          >
        </template>
      </van-field>
      <div class="submitBtn">
        <van-button block type="info" native-type="submit" class="loginBtn">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login, sendSms } from '@/assets/api/user'
// 导入vuex的mutations
import { mapMutations } from 'vuex'

export default {
  name: 'Login',
  data() {
    return {
      // 表单值
      user: {
        mobile: '',
        code: ''
      },
      // 从上到下进行校验
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: '手机号码格式错误'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          { pattern: /^[0-9]{6}$/, message: '验证码格式错误' }
        ]
      },
      // 按钮是否显示
      isSend: false,
      // 倒计时是否显示
      isCountDown: false
    }
  },
  methods: {
    // 导入函数
    ...mapMutations(['saveToken']),
    // 登录功能
    async onSubmit() {
      // 获取表单数据
      const user = this.user
      // 表单验证
      // 提交表单请求登入
      // 在组件中必须通过调用$toast
      // toast只能展示一个，下一个开启上一个结束
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        // 调为0是会一直展示
        duration: 0
      })
      try {
        const res = await login(user)
        this.$toast.success('登入成功')
        const { data } = res
        // 此函数执行过于复杂
        this.saveToken(data.data)
        // 它可能会被先执行,有时候又不好,猜测与网络有关
        setTimeout(() => {
          this.$router.push('/me')
        }, 500)
      } catch (err) {
        if (err.response.status === 400) {
          this.$toast.fail('手机或验证码错误')
        } else if (err.response.status === 403) {
          this.$toast.fail('无效的用户')
        } else {
          this.$toast.fail('服务器繁忙,请稍后再试')
        }
      }
      // 后续操作
    },
    // 发送验证码功能
    async onSendSms() {
      // 1 验证手机号
      try {
        // 成功后没有返回值
        await this.$refs.userForm.validate('手机号')
      } catch (err) {
        return this.$toast.fail('错误的手机号')
      }
      // 显示倒计时，并禁用按钮
      this.isSend = true
      this.isCountDown = true
      const timer = setInterval(() => {
        if (this.verificationText === '0') {
          // 如果显示NAN这是进行了运算
          this.verificationText = '获取验证码'
          this.isSend = false
          // 如果不返回会继续执行下面的函数
          return clearInterval(timer)
        }
        this.verificationText = --this.verificationText + ''
      }, 1000)
      // 3 请求并发送验证码
      try {
        var res = await sendSms(this.user.mobile)
      } catch {
        this.isCountDown = false
        this.isSend = false
        return this.$toast.fail('发送失败请稍后重试')
      }
      this.$toast.success('验证码已经发送')
    },
    // 倒计时结束
    countFinish() {
      this.isCountDown = false
      this.isSend = false
    }
  }
}
</script>

<style lang="less" scoped>
.iconfont {
  font-size: 37px;
}

.verificationBtn {
  padding: 0;
  color: #666 !important;
  width: 152px;
  height: 46px;
  font-size: 22px;
  position: relative;
  top: -4px;
}
.submitBtn {
  padding: 53px 33px;
  .loginBtn {
    padding: 0;
    background-color: #6db4fb;
    border: 0;
  }
}
// 定义倒计时样式
.block {
  display: inline-block;
  width: 152px;
  height: 46px;
  border-radius: 46px;
  line-height: 46px;
  color: #000;
  font-size: 12px;
  text-align: center;
  background-color: #ededed;
}
</style>
